package org.example.liuy;

import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import lombok.extern.slf4j.Slf4j;
import org.example.liuy.handler.AnnotationHandlerMapping;
import org.example.liuy.handler.RateLimitHandler;
import org.example.liuy.handler.RequestLoggingHandler;
import org.example.liuy.service.*;
import org.example.liuy.service.cache.CacheManager;
import org.example.liuy.service.session.IntelligentSessionService;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.*;

/**
 * 主服务类 - 使用工厂模式和门面模式
 */
@Slf4j
public class MyHttpService {

    private final HttpServer server;
    private final IntelligentSessionService sessionManager;
    private final StakeManager stakeManager;
    private final MonitoringService monitoringService;
    private final CacheManager cacheManager;

    public MyHttpService(int port) throws IOException {
        this.monitoringService = MonitoringService.getInstance();
        this.sessionManager = new IntelligentSessionService(monitoringService);
        this.cacheManager = new CacheManager(monitoringService);
        this.stakeManager = new StakeManager(monitoringService, cacheManager, sessionManager);

        this.server = HttpServer.create(new InetSocketAddress(port), 0);

        // 注册控制器
        // 初始化注解处理器映射
        AnnotationHandlerMapping handlerMapping = new AnnotationHandlerMapping(server);
        // 使用组件扫描自动注册控制器
        handlerMapping.scanAndRegisterHandlers("org.example.liuy.controller",
                sessionManager, stakeManager);
        // 构建责任链：日志 -> 限流 -> 验证 -> 路由
        // HttpHandler routingHandler = handlerMapping::handleRequest;
        // HttpHandler validationHandler = new RequestValidationHandler(routingHandler);
        // HttpHandler loggingHandler = new RequestLoggingHandler(validationHandler);
        HttpHandler rateLimitHandler = new RateLimitHandler(handlerMapping::handleRequest);
        HttpHandler loggingHandler = new RequestLoggingHandler(rateLimitHandler);
        server.createContext("/",loggingHandler );

        // 优化线程池配置
        int coreCount = Runtime.getRuntime().availableProcessors();
        server.setExecutor(new ThreadPoolExecutor(
                coreCount * 8,              // 进一步增加核心线程数
                coreCount * 32,             // 增加最大线程数
                60L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(20000), // 增加队列大小
                new ThreadPoolExecutor.CallerRunsPolicy()
        ));
    }

    public void start() {
        server.start();
        sessionManager.start();
        stakeManager.startCleanupTask();
        cacheManager.startCleanupTask();
        monitoringService.startMonitoringTask();

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            stop();
            log.info("Server shutdown completed");
        }));
    }

    public void stop() {
        server.stop(0);
        sessionManager.stop();
        stakeManager.stop();
        cacheManager.stop();
        monitoringService.stop();
    }
}














